//
//  PhotoSelectorViewController.swift
//  Super_WeiBo
//
//  Created by SuperMac on 16/6/12.
//  Copyright © 2016年 lc. All rights reserved.
//

import UIKit

private let PhotoSelectorCellReuseIdentifier = "PhotoSelectorCellReuseIdentifier"
class PhotoSelectorViewController: UIViewController {

    override func viewDidLoad()
    {
        super.viewDidLoad()
        // 设置布局
        setupUI()
    }
    /**
     设置布局
     */
    private func setupUI()
    {
        // 添加子控件
        view.addSubview(collectionView)
        
        // 布局子控件
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        
        // 添加约束
        var cons = [NSLayoutConstraint]()
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["collectionView": collectionView])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["collectionView": collectionView])
        
        view.addConstraints(cons)
    }
    
    // MARK: - 懒加载
    private lazy var collectionView: UICollectionView = {
       let clv = UICollectionView(frame: CGRectZero, collectionViewLayout: PhotoSelectorViewLayout())
        clv.dataSource = self
        clv.registerClass(PhotoSelectorCell.self, forCellWithReuseIdentifier: PhotoSelectorCellReuseIdentifier)
        return clv
    }()
    /// 保存图片数组
    lazy var pictureImages = [UIImage]()
    
}
extension PhotoSelectorViewController: UICollectionViewDataSource,PhotoSelectorCellDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureImages.count + 1
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell  = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoSelectorCellReuseIdentifier, forIndexPath: indexPath) as! PhotoSelectorCell
        cell.photoSelectorCellDelegate = self
        cell.image = (pictureImages.count == indexPath.item) ? nil : pictureImages[indexPath.item]
        return cell
    }
    
    // 实现协议方法
    func photoDidAddSelector(cell: PhotoSelectorCell) {
        // 判断数据源是否可用
        /**
         case PhotoLibrary      不可删除的照片库
         case Camera            相机
         case SavedPhotosAlbum  可删除的照片库
         */
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)
        {
            return
        }
        // 创建图片选择器
        let vc = UIImagePickerController()
        vc.delegate = self
//        vc.allowsEditing = true // 允许用户编辑选中的图片
        presentViewController(vc, animated: true, completion: nil)
    }
    
    func photoDidRemoveSelector(cell: PhotoSelectorCell) {
        // 从数组中移除"当前点击"的图片
        let indexPath = collectionView.indexPathForCell(cell)
        pictureImages.removeAtIndex(indexPath!.item)
        // 刷新表格
        collectionView.reloadData()
    }
    
    // PickerController的代理方法，不现实此方法 PickerController 可以自动消失，实现后需要手动关闭 PickerController
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        // 根据屏幕宽度制作新图片
        let newImage = image.imageWithSecale(UIScreen.mainScreen().bounds.width)
        
        // 添加选择后的图片
        pictureImages.append(newImage)
        
        // 刷新表格
        collectionView.reloadData()
        
        // 关闭图片选择器
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

@objc // 可选协议标识
protocol PhotoSelectorCellDelegate: NSObjectProtocol
{
    optional func photoDidAddSelector(cell: PhotoSelectorCell)
    optional func photoDidRemoveSelector(cell: PhotoSelectorCell)
}
class PhotoSelectorCell: UICollectionViewCell
{
    weak var photoSelectorCellDelegate: PhotoSelectorCellDelegate?
    
    var image: UIImage?{
        didSet{
            if image != nil{
                removeBotton.hidden = false
                addBotton.userInteractionEnabled = false
//                addBotton.setBackgroundImage(image, forState: UIControlState.Normal)
                addBotton.setImage(image, forState: UIControlState.Normal)
            }
            else{
                removeBotton.hidden = true
                addBotton.userInteractionEnabled = true
                addBotton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
//                addBotton.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    private func setupUI()
    {
        // 添加子控件
        contentView.addSubview(addBotton)
        contentView.addSubview(removeBotton)
        
        // 布局子控件
        addBotton.translatesAutoresizingMaskIntoConstraints = false
        removeBotton.translatesAutoresizingMaskIntoConstraints = false
        
        var cons = [NSLayoutConstraint]()
        
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[addBotton]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["addBotton": addBotton])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[addBotton]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["addBotton": addBotton])
        
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-2-[removeBotton]", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["removeBotton": removeBotton])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-2-[removeBotton]", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["removeBotton": removeBotton])
        
        contentView.addConstraints(cons)
        
    }
    // MARK: - 懒加载、
    private lazy var removeBotton: UIButton = {
        let btn = UIButton()
        btn.hidden = true
        btn.setBackgroundImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        btn.addTarget(self, action: #selector(PhotoSelectorCell.removeBtnClick), forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    private lazy var addBotton: UIButton = {
        let btn = UIButton()
        btn.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
//        btn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        btn.addTarget(self, action: #selector(PhotoSelectorCell.addBtnClick), forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 点击事件
    func addBtnClick()
    {
        photoSelectorCellDelegate?.photoDidAddSelector!(self)
    }
    func removeBtnClick()
    {
        photoSelectorCellDelegate?.photoDidRemoveSelector!(self)
    }

    
}
class PhotoSelectorViewLayout: UICollectionViewFlowLayout
{
    override func prepareLayout() {
        super.prepareLayout()
        
        itemSize = CGSize(width: 80, height: 80)
        minimumLineSpacing = 10
        minimumInteritemSpacing = 10
        sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }
}


